﻿using System.Collections.Generic;
using NHibernate;
using NHibernate.Criterion;

namespace HinduShop.DbClassLib
{
    public class ModelsRepository<T> : IRepository<T> where T : class
    {
        readonly IUnitOfWorkFactory unitOfWorkFactory;

        public ModelsRepository()
        {
            unitOfWorkFactory = new UnitOfWorkFactory();
        }

        #region IRepository<T> Members

        public void SaveItem(T item)
        {
            unitOfWorkFactory.CurrentSession.Save(item);
        }

        public IEnumerable<T> ReadAll()
        {
            return unitOfWorkFactory.CurrentSession.CreateCriteria<T>()
                .List<T>();
        }

        public T ReadById(int id)
        {
            return unitOfWorkFactory.CurrentSession.Get<T>(id);
        }

        public void DeleteItem(T item)
        {
            unitOfWorkFactory.CurrentSession.Delete(item);
        }

        public void UpdateItem(T item)
        {
            unitOfWorkFactory.CurrentSession.Update(item);
        }

        public T ReadByName(string columnName, string objName)
        {
            T obj = unitOfWorkFactory.CurrentSession
                .CreateCriteria(typeof (T))
                .Add(Restrictions.Eq(columnName, objName))
                .UniqueResult<T>();

            return obj;
        }

        #endregion
    }
}